package connect_tx_sdk.utils;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import connect_tx_sdk.config.QQConfig;

/**
 * 
 * @创建作者：hiyoucai@126.com
 * @创建时间：2011-6-17 下午04:55:41
 * @文件描述：处理通用类库
 */
public class ConnectUtils {

	public static String getOauthNonce() {
		String str = Math.random() + "";
		return str.replaceFirst("^\\d.", "");
	}

	public static String getOauthTimestamp() {
		String str = new Date().getTime() / 1000 + "";
		return str;
	}

	public static String getOauthversion() {
		return "1.0";
	}

	public static String getOauthSignatureMethod() {
		return "HMAC-SHA1";
	}

	public static String getOauthSignature(String method, String url, List<NameValuePair> parameters, String oauth_token_secret) {
		try {
			String stepA1 = method;
			String stepA2 = URLEncoder.encode(url, "UTF-8");
			String stepA3 = getSerialParameters(parameters, false);
			String stepA = stepA1 + "&" + stepA2 + "&" + stepA3;
			String stepB = QQConfig.appkey + "&" + oauth_token_secret;
			return SecretUtils.getBase64Mac(stepA, stepB);
		} catch (Exception e) {
			return "";
		}
	}

	public static String getSerialParameters(List<NameValuePair> parameters, boolean onlySerialValue) {
		try {
			String str = "";
			for (int i = 0; i < parameters.size(); i++) {
				NameValuePair item = parameters.get(i);
				if (onlySerialValue) {
					str += item.getName() + "=" + URLEncoder.encode(item.getValue(), "UTF-8");

				} else {
					str += item.getName() + "=" + item.getValue();
				}
				if (i < parameters.size() - 1) {
					str += "&";
				}
			}
			if (!onlySerialValue) {
				str = URLEncoder.encode(str, "UTF-8");
			}
			return str;
		} catch (Exception e) {
			return "";
		}
	}

	public static Map<String, String> parseTokenResult(String result) {
		Map<String, String> m = new HashMap<String, String>();
		if (result == null) {
			return m;
		}
		String[] rs = result.split("&");
		if (rs.length < 1) {
			return m;
		}
		for (int i = 0; i < rs.length; i++) {
			String item = rs[i];
			String[] sub = item.split("=");
			if (sub.length < 1) {
				continue;
			}
			String key = sub[0];
			String value = sub[1];
			m.put(key, value);
		}
		return m;
	}

	public static String decodeParameter(String value) {
		int nCount = 0;
		for (int i = 0; i < value.length(); i++) {
			if (value.charAt(i) == '%') {
				i += 2;
			}
			nCount++;
		}
		byte[] sb = new byte[nCount];
		for (int i = 0, index = 0; i < value.length(); i++) {
			if (value.charAt(i) != '%') {
				sb[index++] = (byte) value.charAt(i);
			} else {
				StringBuilder sChar = new StringBuilder();
				sChar.append(value.charAt(i + 1));
				sChar.append(value.charAt(i + 2));
				sb[index++] = Integer.valueOf(sChar.toString(), 16).byteValue();
				i += 2;
			}
		}
		String decode = "";
		try {
			decode = new String(sb, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return decode;
	}

	public static boolean verifyOpenId(String openid, String timestamp, String oauth_signature, String appkey) {
		String str = openid + timestamp;
		String signature = SecretUtils.getBase64Mac(str, appkey);
		return signature.equals(decodeParameter(oauth_signature));
	}

	public static Map<String, Object> parseXmlToMap(String xml) throws Exception {
		Map<String, Object> oXml = new HashMap<String, Object>();
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		InputStream is = IOUtils.toInputStream(xml, "UTF-8");
		Document doc = docBuilder.parse(is);
		Element root = doc.getDocumentElement();
		NodeList nodeList = root.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node n = nodeList.item(i);
			if (n.getNodeType() == 1) {
				Element ne = (Element) n;
				String key = ne.getNodeName();
				String value = ne.getTextContent();
				oXml.put(key, value);
			}
		}
		return oXml;
	}

	public static void main(String[] args) throws Exception {
		if (false) {
			System.out.print(verifyOpenId("6ED93B1934A4178F6E799C5180484D26", "1308299554", "LQutajTIXdHzZB8YDQZwTLzIruM=", QQConfig.appkey));
		}
		if (true) {
			Map<String, Object> oXml = parseXmlToMap("<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><ret>0</ret><msg></msg><nickname>神狗再现</nickname><figureurl>http://qzapp.qlogo.cn/qzapp/208641/6ED93B1934A4178F6E799C5180484D26/30</figureurl><figureurl_1>http://qzapp.qlogo.cn/qzapp/208641/6ED93B1934A4178F6E799C5180484D26/50</figureurl_1><figureurl_2>http://qzapp.qlogo.cn/qzapp/208641/6ED93B1934A4178F6E799C5180484D26/100</figureurl_2></data>");
			System.out.println(oXml);
		}
	}

}
